from flask import Flask, request, jsonify, render_template_string, send_from_directory, Response
from flask_cors import CORS
import os
import csv
import io
from datetime import datetime, date
from decimal import Decimal
from db import get_conn
from config import get_config
import argparse

app = Flask(__name__)
CORS(app)

# 加载配置
app.config.from_object(get_config())

def convert_types(obj):
    """将Decimal、datetime和date对象转换为JSON兼容类型"""
    if isinstance(obj, Decimal):
        return float(obj)
    if isinstance(obj, (datetime, date)):
        return obj.isoformat()
    if isinstance(obj, list):
        return [convert_types(item) for item in obj]
    if isinstance(obj, dict):
        return {key: convert_types(value) for key, value in obj.items()}
    if isinstance(obj, tuple):
        return tuple(convert_types(item) for item in obj)
    return obj

# 主页和静态文件路由
@app.route('/')
def index():
    return send_from_directory('.', 'bank.html')

@app.route('/test')
def test_page():
    return send_from_directory('.', 'test_page.html')

@app.route('/static/<path:filename>')
def static_files(filename):
    return send_from_directory('static', filename)

# ==================== 客户功能模块 ====================

# 登录接口
@app.route('/api/login', methods=['POST'])
def login():
    data = request.json
    username = data.get('username')
    password = data.get('password')
    role = data.get('role')
    
    try:
        conn = get_conn()
        cursor = conn.cursor()
        user = None
        
        if role == 'customer':
            sql = "SELECT c.*, u.customerName FROM cardinfo c JOIN userinfo u ON c.customerID = u.customerID WHERE c.cardID=%s AND c.pass=%s"
            cursor.execute(sql, (username, password))
            user = cursor.fetchone()
            if user and user.get('IsReportLoss') == '是':
                return jsonify({'success': False, 'msg': '银行卡已挂失，请联系银行'})
        else:
            if username == 'admin' and password == '123456':
                user = {'customerID': 'ADMIN', 'customerName': '管理员', 'role': 'admin'}
        
        cursor.close()
        conn.close()
        
        if user:
            return jsonify({'success': True, 'msg': '登录成功', 'user': convert_types(user)})
        else:
            return jsonify({'success': False, 'msg': '账号或密码错误'})
    except Exception as e:
        return jsonify({'success': False, 'msg': f'数据库连接错误: {str(e)}'})

# 获取账户信息
@app.route('/api/account_info', methods=['GET'])
def get_account_info():
    cardid = request.args.get('cardid')
    try:
        conn = get_conn()
        cursor = conn.cursor()
        cursor.execute("""
            SELECT c.*, u.customerName, d.savingName 
            FROM cardinfo c 
            JOIN userinfo u ON c.customerID = u.customerID 
            LEFT JOIN deposit d ON c.savingID = d.savingID 
            WHERE c.cardID=%s
        """, (cardid,))
        account = cursor.fetchone()
        cursor.close()
        conn.close()
        
        if account:
            return jsonify({'success': True, 'account': convert_types(account)})
        else:
            return jsonify({'success': False, 'msg': '账户不存在'})
    except Exception as e:
        return jsonify({'success': False, 'msg': f'数据库连接错误: {str(e)}'})

# 存款
@app.route('/api/deposit', methods=['POST'])
def deposit():
    data = request.json
    cardid = data.get('cardid')
    amount = float(data.get('amount'))
    
    try:
        conn = get_conn()
        cursor = conn.cursor()
        
        cursor.execute("SELECT IsReportLoss FROM cardinfo WHERE cardID=%s", (cardid,))
        card = cursor.fetchone()
        if not card or card.get('IsReportLoss') == '是':
            msg = '账户已挂失，无法操作' if card else '账户不存在'
            return jsonify({'success': False, 'msg': msg})
        
        cursor.execute("UPDATE cardinfo SET balance = balance + %s WHERE cardID=%s", (amount, cardid))
        cursor.execute("INSERT INTO tradeinfo (tradeType, cardID, tradeMoney, remark, tradeDate) VALUES (%s, %s, %s, %s, NOW())",
                       ('存款', cardid, amount, f'存款 {amount:.2f} 元'))
        
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({'success': True, 'msg': f'存款成功，金额：{amount:.2f}元'})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'msg': f'存款失败: {str(e)}'})

# 取款
@app.route('/api/withdraw', methods=['POST'])
def withdraw():
    data = request.json
    cardid, amount, password = data.get('cardid'), float(data.get('amount')), data.get('password')
    
    try:
        conn = get_conn()
        cursor = conn.cursor()
        
        cursor.execute("SELECT balance, pass, IsReportLoss FROM cardinfo WHERE cardID=%s", (cardid,))
        card = cursor.fetchone()
        
        if not card: return jsonify({'success': False, 'msg': '账户不存在'})
        if card.get('IsReportLoss') == '是': return jsonify({'success': False, 'msg': '账户已挂失'})
        if card.get('pass') != password: return jsonify({'success': False, 'msg': '密码错误'})
        if card.get('balance') < amount: return jsonify({'success': False, 'msg': '余额不足'})
        
        cursor.execute("UPDATE cardinfo SET balance = balance - %s WHERE cardID=%s", (amount, cardid))
        cursor.execute("INSERT INTO tradeinfo (tradeType, cardID, tradeMoney, remark, tradeDate) VALUES (%s, %s, %s, %s, NOW())",
                       ('取款', cardid, -amount, f'取款 {amount:.2f} 元'))
        
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({'success': True, 'msg': f'取款成功，金额：{amount:.2f}元'})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'msg': f'取款失败: {str(e)}'})

# 转账
@app.route('/api/transfer', methods=['POST'])
def transfer():
    data = request.json
    from_card, to_card, amount, password = data.get('from_card'), data.get('to_card'), float(data.get('amount')), data.get('password')
    
    try:
        conn = get_conn()
        cursor = conn.cursor()
        
        cursor.execute("SELECT balance, pass, IsReportLoss FROM cardinfo WHERE cardID=%s", (from_card,))
        from_account = cursor.fetchone()
        
        if not from_account: return jsonify({'success': False, 'msg': '转出账户不存在'})
        if from_account.get('IsReportLoss') == '是': return jsonify({'success': False, 'msg': '转出账户已挂失'})
        if from_account.get('pass') != password: return jsonify({'success': False, 'msg': '密码错误'})
        if from_account.get('balance') < amount: return jsonify({'success': False, 'msg': '余额不足'})
        
        cursor.execute("SELECT IsReportLoss FROM cardinfo WHERE cardID=%s", (to_card,))
        to_account = cursor.fetchone()
        if not to_account: return jsonify({'success': False, 'msg': '转入账户不存在'})
        if to_account.get('IsReportLoss') == '是': return jsonify({'success': False, 'msg': '转入账户已挂失'})
        
        cursor.execute("UPDATE cardinfo SET balance = balance - %s WHERE cardID=%s", (amount, from_card))
        cursor.execute("UPDATE cardinfo SET balance = balance + %s WHERE cardID=%s", (amount, to_card))
        
        cursor.execute("INSERT INTO tradeinfo (tradeType, cardID, tradeMoney, remark, tradeDate) VALUES (%s, %s, %s, %s, NOW())",
                       ('转账', from_card, -amount, f'转账至 {to_card}'))
        cursor.execute("INSERT INTO tradeinfo (tradeType, cardID, tradeMoney, remark, tradeDate) VALUES (%s, %s, %s, %s, NOW())",
                       ('转账', to_card, amount, f'来自 {from_card}'))
        
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({'success': True, 'msg': f'转账成功，金额：{amount:.2f}元'})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'msg': f'转账失败: {str(e)}'})

# 查询交易记录
@app.route('/api/records', methods=['GET'])
def records():
    cardid = request.args.get('cardid')
    try:
        conn = get_conn()
        cursor = conn.cursor()
        cursor.execute("""
            SELECT tradeID, tradeDate, tradeType, tradeMoney, remark 
            FROM tradeinfo 
            WHERE cardID=%s 
            ORDER BY tradeDate DESC 
            LIMIT 50
        """, (cardid,))
        records = cursor.fetchall()
        cursor.close()
        conn.close()
        return jsonify({'success': True, 'records': convert_types(records)})
    except Exception as e:
        return jsonify({'success': False, 'msg': f'查询失败: {str(e)}'})

# 挂失银行卡
@app.route('/api/report_loss', methods=['POST'])
def report_loss():
    data = request.json
    cardid, reason = data.get('cardid'), data.get('reason')
    
    try:
        conn = get_conn()
        cursor = conn.cursor()
        
        cursor.execute("UPDATE cardinfo SET IsReportLoss='是' WHERE cardID=%s AND IsReportLoss='否'", (cardid,))
        if cursor.rowcount == 0:
            return jsonify({'success': False, 'msg': '账户不存在或已挂失'})

        cursor.execute("INSERT INTO tradeinfo (tradeType, cardID, tradeMoney, remark, tradeDate) VALUES (%s, %s, %s, %s, NOW())",
                       ('挂失', cardid, 0.00, f'银行卡挂失 - {reason}'))
        
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({'success': True, 'msg': '挂失成功'})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'msg': f'挂失失败: {str(e)}'})

# 修改密码
@app.route('/api/change_password', methods=['POST'])
def change_password():
    data = request.json
    cardid, old_pwd, new_pwd = data.get('cardid'), data.get('old_password'), data.get('new_password')
    
    try:
        conn = get_conn()
        cursor = conn.cursor()
        
        cursor.execute("SELECT pass, IsReportLoss FROM cardinfo WHERE cardID=%s", (cardid,))
        card = cursor.fetchone()

        if not card: return jsonify({'success': False, 'msg': '账户不存在'})
        if card.get('IsReportLoss') == '是': return jsonify({'success': False, 'msg': '账户已挂失'})
        if card.get('pass') != old_pwd: return jsonify({'success': False, 'msg': '原密码错误'})
        
        cursor.execute("UPDATE cardinfo SET pass=%s WHERE cardID=%s", (new_pwd, cardid))
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({'success': True, 'msg': '密码修改成功'})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'msg': f'密码修改失败: {str(e)}'})

# ==================== 管理员通用接口 ====================
def get_all_entities(entity_name, query):
    try:
        conn = get_conn()
        cursor = conn.cursor()
        cursor.execute(query)
        entities = cursor.fetchall()
        cursor.close()
        conn.close()
        return jsonify({'success': True, 'data': convert_types(entities)})
    except Exception as e:
        return jsonify({'success': False, 'msg': f'查询失败: {str(e)}'})

def delete_entity(entity_name, table_name, id_column, entity_id, check_query=None):
    try:
        conn = get_conn()
        cursor = conn.cursor()
        
        if check_query:
            cursor.execute(check_query['query'], check_query['params'])
            result = cursor.fetchone()
            if result and result['count'] > 0:
                return jsonify({'success': False, 'msg': check_query['msg'].format(count=result['count'])})
        
        cursor.execute(f"DELETE FROM {table_name} WHERE {id_column}=%s", (entity_id,))
        if cursor.rowcount == 0:
            return jsonify({'success': False, 'msg': '记录未找到或无法删除'})
            
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({'success': True, 'msg': f'{entity_name}删除成功'})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'msg': f'删除失败: {str(e)}'})

# ==================== 管理员具体模块 ====================

@app.route('/api/admin/customers', methods=['GET'])
def get_all_customers():
    pid = request.args.get('pid')
    if pid:
        result = get_all_entities('customers', f"SELECT * FROM userinfo WHERE PID LIKE '%{pid}%' ORDER BY customerID")
    else:
        result = get_all_entities('customers', "SELECT * FROM userinfo ORDER BY customerID")
    
    # 调试输出
    response_data = result.get_json() if hasattr(result, 'get_json') else result
    print('【后端调试】返回客户数据:', response_data)
    
    return result

@app.route('/api/admin/customers', methods=['POST'])
def add_customer():
    data = request.json
    print('【后端收到的客户数据】', data)
    try:
        conn = get_conn()
        cursor = conn.cursor()
        # 检查身份证号是否已存在
        cursor.execute("SELECT customerID FROM userinfo WHERE PID=%s", (data.get('PID'),))
        if cursor.fetchone():
            return jsonify({'success': False, 'msg': '身份证号已存在'})
        # 参照编辑逻辑处理客户姓名
        customer_name = data.get('customerName', '').strip()
        cursor.execute("""
            INSERT INTO userinfo (customerName, PID, telephone, address)
            VALUES (%s, %s, %s, %s)
        """, (customer_name, data.get('PID'), data.get('telephone'), data.get('address')))
        conn.commit()
        cursor.execute("SELECT * FROM userinfo WHERE PID=%s", (data.get('PID'),))
        inserted = cursor.fetchone()
        print('【插入后数据库中的客户】', inserted)
        cursor.close()
        conn.close()
        return jsonify({'success': True, 'msg': '客户添加成功', 'customer': convert_types(inserted)})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'msg': f'添加客户失败: {str(e)}'})

@app.route('/api/admin/customers/<int:customer_id>', methods=['PUT'])
def update_customer(customer_id):
    data = request.json
    try:
        conn = get_conn()
        cursor = conn.cursor()
        
        # 检查客户是否存在
        cursor.execute("SELECT customerID FROM userinfo WHERE customerID=%s", (customer_id,))
        if not cursor.fetchone():
            return jsonify({'success': False, 'msg': '客户不存在'})
        
        # 检查身份证号是否被其他客户使用
        cursor.execute("SELECT customerID FROM userinfo WHERE PID=%s AND customerID!=%s", (data.get('PID'), customer_id))
        if cursor.fetchone():
            return jsonify({'success': False, 'msg': '身份证号已被其他客户使用'})
        
        # 确保客户姓名不为None，如果为空则设为空字符串
        customer_name = data.get('customerName', '').strip() if data.get('customerName') else ''
        
        cursor.execute("""
            UPDATE userinfo SET customerName=%s, PID=%s, telephone=%s, address=%s 
            WHERE customerID=%s
        """, (customer_name, data.get('PID'), data.get('telephone'), data.get('address'), customer_id))
        
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({'success': True, 'msg': '客户信息更新成功'})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'msg': f'更新客户失败: {str(e)}'})

@app.route('/api/admin/customers/<int:customer_id>', methods=['GET'])
def get_customer(customer_id):
    try:
        conn = get_conn()
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM userinfo WHERE customerID=%s", (customer_id,))
        customer = cursor.fetchone()
        cursor.close()
        conn.close()
        
        if customer:
            return jsonify({'success': True, 'customer': convert_types(customer)})
        else:
            return jsonify({'success': False, 'msg': '客户不存在'})
    except Exception as e:
        return jsonify({'success': False, 'msg': f'获取客户信息失败: {str(e)}'})

@app.route('/api/admin/customers/<customer_id>', methods=['DELETE'])
def delete_customer(customer_id):
    check = {
        'query': "SELECT COUNT(*) as count FROM cardinfo WHERE customerID=%s",
        'params': (customer_id,),
        'msg': '该客户还有{count}张银行卡，无法删除'
    }
    return delete_entity('客户', 'userinfo', 'customerID', customer_id, check)

@app.route('/api/admin/cards', methods=['GET'])
def get_all_cards():
    cardid = request.args.get('cardid')
    query = """
        SELECT c.*, u.customerName, d.savingName 
        FROM cardinfo c 
        JOIN userinfo u ON c.customerID = u.customerID 
        LEFT JOIN deposit d ON c.savingID = d.savingID 
    """
    if cardid:
        query += f" WHERE c.cardID LIKE '%{cardid}%'"
    query += " ORDER BY c.cardID"
    return get_all_entities('cards', query)

@app.route('/api/admin/cards', methods=['POST'])
def add_card():
    data = request.json
    try:
        conn = get_conn()
        cursor = conn.cursor()
        
        # 检查卡号是否已存在
        cursor.execute("SELECT cardID FROM cardinfo WHERE cardID=%s", (data.get('cardID'),))
        if cursor.fetchone():
            return jsonify({'success': False, 'msg': '银行卡号已存在'})
        
        # 检查客户是否存在
        cursor.execute("SELECT customerID FROM userinfo WHERE customerID=%s", (data.get('customerID'),))
        if not cursor.fetchone():
            return jsonify({'success': False, 'msg': '客户不存在'})
        
        cursor.execute("""
            INSERT INTO cardinfo (cardID, customerID, savingID, balance, pass, IsReportLoss) 
            VALUES (%s, %s, %s, %s, %s, %s)
        """, (data.get('cardID'), data.get('customerID'), data.get('savingID'), 
              data.get('balance', 0), data.get('pass'), data.get('IsReportLoss', '否')))
        
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({'success': True, 'msg': '银行卡添加成功'})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'msg': f'添加银行卡失败: {str(e)}'})

@app.route('/api/admin/cards/<card_id>', methods=['PUT'])
def update_card(card_id):
    data = request.json
    try:
        conn = get_conn()
        cursor = conn.cursor()
        
        # 检查银行卡是否存在
        cursor.execute("SELECT cardID FROM cardinfo WHERE cardID=%s", (card_id,))
        if not cursor.fetchone():
            return jsonify({'success': False, 'msg': '银行卡不存在'})
        
        # 检查客户是否存在
        cursor.execute("SELECT customerID FROM userinfo WHERE customerID=%s", (data.get('customerID'),))
        if not cursor.fetchone():
            return jsonify({'success': False, 'msg': '客户不存在'})
        
        cursor.execute("""
            UPDATE cardinfo SET customerID=%s, savingID=%s, balance=%s, pass=%s, IsReportLoss=%s 
            WHERE cardID=%s
        """, (data.get('customerID'), data.get('savingID'), data.get('balance'), 
              data.get('pass'), data.get('IsReportLoss'), card_id))
        
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({'success': True, 'msg': '银行卡信息更新成功'})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'msg': f'更新银行卡失败: {str(e)}'})

@app.route('/api/admin/cards/<card_id>', methods=['GET'])
def get_card(card_id):
    try:
        conn = get_conn()
        cursor = conn.cursor()
        cursor.execute("""
            SELECT c.*, u.customerName, d.savingName 
            FROM cardinfo c 
            JOIN userinfo u ON c.customerID = u.customerID 
            LEFT JOIN deposit d ON c.savingID = d.savingID 
            WHERE c.cardID=%s
        """, (card_id,))
        card = cursor.fetchone()
        cursor.close()
        conn.close()
        
        if card:
            return jsonify({'success': True, 'card': convert_types(card)})
        else:
            return jsonify({'success': False, 'msg': '银行卡不存在'})
    except Exception as e:
        return jsonify({'success': False, 'msg': f'获取银行卡信息失败: {str(e)}'})

@app.route('/api/admin/cards/<card_id>', methods=['DELETE'])
def delete_card(card_id):
    check = {
        'query': "SELECT COUNT(*) as count FROM tradeinfo WHERE cardID=%s",
        'params': (card_id,),
        'msg': '该银行卡还有{count}条交易记录，无法删除'
    }
    return delete_entity('银行卡', 'cardinfo', 'cardID', card_id, check)

@app.route('/api/admin/deposits', methods=['GET'])
def get_all_deposits():
    saving_name = request.args.get('saving_name')
    if saving_name:
        return get_all_entities('deposits', f"SELECT * FROM deposit WHERE savingName LIKE '%{saving_name}%' ORDER BY savingID")
    return get_all_entities('deposits', "SELECT * FROM deposit ORDER BY savingID")

@app.route('/api/admin/deposits', methods=['POST'])
def add_deposit():
    data = request.json
    try:
        conn = get_conn()
        cursor = conn.cursor()
        
        # 检查业务名称是否已存在
        cursor.execute("SELECT savingID FROM deposit WHERE savingName=%s", (data.get('savingName'),))
        if cursor.fetchone():
            return jsonify({'success': False, 'msg': '存款业务名称已存在'})
        
        cursor.execute("""
            INSERT INTO deposit (savingName, descrip) 
            VALUES (%s, %s)
        """, (data.get('savingName'), data.get('descrip', '')))
        
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({'success': True, 'msg': '存款业务添加成功'})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'msg': f'添加存款业务失败: {str(e)}'})

@app.route('/api/admin/deposits/<int:deposit_id>', methods=['PUT'])
def update_deposit(deposit_id):
    data = request.json
    try:
        conn = get_conn()
        cursor = conn.cursor()
        
        # 检查存款业务是否存在
        cursor.execute("SELECT savingID FROM deposit WHERE savingID=%s", (deposit_id,))
        if not cursor.fetchone():
            return jsonify({'success': False, 'msg': '存款业务不存在'})
        
        # 检查业务名称是否被其他业务使用
        cursor.execute("SELECT savingID FROM deposit WHERE savingName=%s AND savingID!=%s", (data.get('savingName'), deposit_id))
        if cursor.fetchone():
            return jsonify({'success': False, 'msg': '存款业务名称已被其他业务使用'})
        
        cursor.execute("""
            UPDATE deposit SET savingName=%s, descrip=%s 
            WHERE savingID=%s
        """, (data.get('savingName'), data.get('descrip', ''), deposit_id))
        
        conn.commit()
        cursor.close()
        conn.close()
        return jsonify({'success': True, 'msg': '存款业务更新成功'})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'msg': f'更新存款业务失败: {str(e)}'})

@app.route('/api/admin/deposits/<int:deposit_id>', methods=['GET'])
def get_deposit(deposit_id):
    try:
        conn = get_conn()
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM deposit WHERE savingID=%s", (deposit_id,))
        deposit = cursor.fetchone()
        cursor.close()
        conn.close()
        
        if deposit:
            return jsonify({'success': True, 'deposit': convert_types(deposit)})
        else:
            return jsonify({'success': False, 'msg': '存款业务不存在'})
    except Exception as e:
        return jsonify({'success': False, 'msg': f'获取存款业务信息失败: {str(e)}'})

@app.route('/api/admin/deposits/<int:deposit_id>', methods=['DELETE'])
def delete_deposit(deposit_id):
    check = {
        'query': "SELECT COUNT(*) as count FROM cardinfo WHERE savingID=%s",
        'params': (deposit_id,),
        'msg': '该存款类型还有{count}张银行卡在使用，无法删除'
    }
    return delete_entity('存款业务', 'deposit', 'savingID', deposit_id, check)

@app.route('/api/admin/transactions', methods=['GET'])
def get_all_transactions():
    cardid = request.args.get('cardid')
    query = """
        SELECT t.*, u.customerName 
        FROM tradeinfo t 
        JOIN cardinfo c ON t.cardID = c.cardID 
        JOIN userinfo u ON c.customerID = u.customerID 
    """
    if cardid:
        query += f" WHERE t.cardID LIKE '%{cardid}%'"
    query += " ORDER BY t.tradeDate DESC"
    return get_all_entities('transactions', query)

@app.route('/api/admin/transactions/<int:transaction_id>', methods=['DELETE'])
def delete_transaction(transaction_id):
    return delete_entity('交易记录', 'tradeinfo', 'tradeID', transaction_id)

# ==================== 高级搜索模块 ====================

@app.route('/api/admin/advanced_search', methods=['POST'])
def advanced_search():
    data = request.json
    entity_type = data.get('entity_type')
    search_type = data.get('search_type')
    search_field = data.get('search_field')
    search_value = data.get('search_value')
    
    try:
        conn = get_conn()
        cursor = conn.cursor()
        
        if entity_type == 'customers':
            if search_field == 'customerName':
                query = "SELECT * FROM userinfo WHERE customerName LIKE %s ORDER BY customerID"
                search_param = f'%{search_value}%'
            elif search_field == 'PID':
                query = "SELECT * FROM userinfo WHERE PID LIKE %s ORDER BY customerID"
                search_param = f'%{search_value}%'
            elif search_field == 'telephone':
                query = "SELECT * FROM userinfo WHERE telephone LIKE %s ORDER BY customerID"
                search_param = f'%{search_value}%'
            else:
                return jsonify({'success': False, 'msg': '不支持的搜索字段'})
            
            cursor.execute(query, (search_param,))
            results = cursor.fetchall()
            
        else:
            return jsonify({'success': False, 'msg': '不支持的实体类型'})
        
        cursor.close()
        conn.close()
        
        return jsonify({'success': True, 'data': convert_types(results)})
        
    except Exception as e:
        return jsonify({'success': False, 'msg': f'搜索失败: {str(e)}'})

# ==================== CSV导出模块 ====================

def export_csv_response(filename, headers, data):
    output = io.StringIO()
    writer = csv.writer(output)
    writer.writerow(headers)
    writer.writerows(data)
    output.seek(0)
    return Response(
        output.getvalue(),
        mimetype='text/csv',
        headers={'Content-Disposition': f'attachment; filename={filename}'}
    )

@app.route('/api/admin/customers/export', methods=['GET'])
def export_customers_csv():
    conn = get_conn()
    cursor = conn.cursor()
    cursor.execute("SELECT customerID, customerName, PID, telephone, address FROM userinfo ORDER BY customerID")
    customers = [list(c.values()) for c in cursor.fetchall()]
    cursor.close()
    conn.close()
    headers = ['客户编号', '客户姓名', '身份证号', '联系电话', '联系地址']
    return export_csv_response('customers.csv', headers, customers)

@app.route('/api/admin/cards/export', methods=['GET'])
def export_cards_csv():
    conn = get_conn()
    cursor = conn.cursor()
    cursor.execute("""
        SELECT c.cardID, u.customerName, c.customerID, d.savingName, c.openDate, c.openMoney, c.balance, c.IsReportLoss 
        FROM cardinfo c 
        JOIN userinfo u ON c.customerID = u.customerID 
        LEFT JOIN deposit d ON c.savingID = d.savingID 
        ORDER BY c.cardID
    """)
    cards = [list(convert_types(c).values()) for c in cursor.fetchall()]
    cursor.close()
    conn.close()
    headers = ['卡号', '客户姓名', '客户编号', '存款类型', '开户日期', '开户金额', '余额', '是否挂失']
    return export_csv_response('cards.csv', headers, cards)

@app.route('/api/admin/deposits/export', methods=['GET'])
def export_deposits_csv():
    conn = get_conn()
    cursor = conn.cursor()
    cursor.execute("SELECT savingID, savingName, descrip FROM deposit ORDER BY savingID")
    deposits = [list(d.values()) for d in cursor.fetchall()]
    cursor.close()
    conn.close()
    headers = ['业务编号', '业务名称', '业务描述']
    return export_csv_response('deposits.csv', headers, deposits)

@app.route('/api/admin/transactions/export', methods=['GET'])
def export_transactions_csv():
    conn = get_conn()
    cursor = conn.cursor()
    cursor.execute("""
        SELECT t.tradeDate, t.tradeType, t.cardID, u.customerName, t.tradeMoney, t.remark 
        FROM tradeinfo t 
        JOIN cardinfo c ON t.cardID = c.cardID 
        JOIN userinfo u ON c.customerID = u.customerID 
        ORDER BY t.tradeDate DESC
    """)
    transactions = [list(convert_types(t).values()) for t in cursor.fetchall()]
    cursor.close()
    conn.close()
    headers = ['交易时间', '交易类型', '卡号', '客户姓名', '交易金额', '备注']
    return export_csv_response('transactions.csv', headers, transactions)

# ==================== 启动 ====================

@app.route('/api/test', methods=['GET'])
def test_connection():
    return jsonify({'success': True, 'msg': '后端连接正常'})

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Banking System Flask App')
    parser.add_argument('--env', choices=['development', 'production'], default='development', help='Environment')
    parser.add_argument('--host', default='127.0.0.1', help='Host to bind to')
    parser.add_argument('--port', type=int, default=5000, help='Port to bind to')
    
    args = parser.parse_args()
    os.environ['FLASK_ENV'] = args.env
    
    if args.env == 'production':
        from waitress import serve
        print(f"🚀 启动生产环境服务器 at http://{args.host}:{args.port}")
        serve(app, host=args.host, port=args.port)
    else:
        print(f"🔧 启动开发环境服务器 at http://{args.host}:{args.port}")
        app.run(host=args.host, port=args.port, debug=True) 